01. Function-Level Scope

Function-Level Scope

Question:

The scope of variables (including functions and objects) within a program describes which objects (and functions) can access them and from which objects they aren't accessible.

JavaScript includes function level scope, which means that variables declared within a function are only available inside that function.

We're going to walk through a few challenges where you'll explore what scope means in JavaScript.

Your Challenge

In this quiz, you're going to see two different snippets of code that are entirely the same except for one difference. See if you can predict the results of each.

Click "Continue to quiz" when you're ready to get started!

Start Quiz:

Solution:

Example 1

var outsideExample = "First string";
function example() {
    var outsideExample = "Second string";
}
example();
console.log(outsideExample); // "First string"

Example 2

var outsideExample = "First string";
function example() {
    outsideExample = "Second string";
}
example();
console.log(outsideExample); // "Second string"

In the first example, notice that we're using var within example(). var means we're declaring a new outsideExample variable within example(). There are two outsideExamples in our program, one with a global scope ("First string") and one with a function-level scope inside example().

After we run example() and try to log outsideExample, we'll log the global version of outsideExample, which is "First string" because console.log() doesn't have access to the version of outsideExample that was created within example().

A global scope means that the variable is accessible anywhere inside our program, which is why we don't need to use var in example 2. In example 2, there's only one version of outsideExample because we aren't declaring a new variable inside example(). Instead we're simply modifying the value of the original global variable outsideExample, which is why we log "Second string" at the end of example 2.

To learn more, check out this in-depth article on JavaScript scope.

INSTRUCTOR NOTE:

Follow your instructors!

@cwpittman

+jameswilliams

Remember, you can always try running this code yourself to see what happens! Here's the code for easy copy/pasting into the console.

Example 1

var outsideExample = "First string";
function example() {
    var outsideExample = "Second string";
}
example();
console.log(outsideExample);

Example 2

var outsideExample = "First string";
function example() {
    outsideExample = "Second string";
}
example();
console.log(outsideExample);